package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findByPage(queryString);
        List<Role> result = page.getResult();
        long total = page.getTotal();
        return new PageResult(total,result);
    }

    @Override
    public List<Menu> findAllMenu() {
        return roleDao.findAllMenu();
    }

    @Override
    public List<Integer> findCheckitemIdsByUsername(String username) {
        return roleDao.findCheckitemIdsByUsername(username);
    }

    @Override
    public void editRoleMenu(String username, Integer[] checkitemIds) {
         roleDao.deleteByRoleName(username);
         //根据角色名查询角色id
        int id= roleDao.findRoleId(username);
        //根据角色id循环插入数据
        if(checkitemIds!=null && checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Object> map = new HashMap<>();
                map.put("role_id",id);
                map.put("menu_id",checkitemId);
                roleDao.insert(map);
            }

        }

    }
}
